<script setup lang="ts">
import { sendMobileCode, loginByQQ, bindMobile } from '@/services/user'
import { mobileRule, codeRule } from '@/utils/rules'
import { showSuccessToast, type FormInstance } from 'vant'
import { onMounted } from 'vue'
import { onUnmounted } from 'vue'
import { ref } from 'vue'
import { useUserStore } from '@/stores/index'
import { useRouter } from 'vue-router'

// 表单数据
const mobile = ref('')
const code = ref('')

// 发送验证码
const time = ref(0)
let timeId: number
const form = ref<FormInstance | null>(null)
const send = async () => {
  // 已经倒计时time的值大于0，此时不能发送验证码
  if (time.value > 0) return
  // 验证不通过报错，阻止程序继续执行
  await form.value?.validate('mobile')
  // 发送短信验证码
  await sendMobileCode(mobile.value, 'bindMobile')
  showSuccessToast('发送成功')
  // 倒计时
  time.value = 60
  if (timeId) clearInterval(timeId)
  timeId = setInterval(() => {
    time.value--
    if (time.value <= 0) clearInterval(timeId)
  }, 1000)
}

// 组件卸载时，清除定时器
onUnmounted(() => {
  clearInterval(timeId)
})

const userStore = useUserStore()
const router = useRouter()
const isBind = ref(true)

const id = ref('')
// 获取openId
onMounted(() => {
  if (QC.Login.check()) {
    // qq登录成功
    QC.Login.getMe((openId: string) => {
      // 获取openId
      console.log(openId)
      id.value = openId
      loginByQQ({
        openId,
        source: 'qq'
      })
        .then((res) => {
          // 登录成功（绑定过手机号）
          // 提示用户
          showSuccessToast('登录成功')
          // 存储用户信息
          userStore.setUser(res.data)
          // 跳转到”我的“页面
          router.replace('/user')
        })
        .catch((error) => {
          // 登录不成功（没绑定过手机号）
          isBind.value = false
        })
    })
  }
})

// 绑定手机号
const bind = async () => {
  const res = await bindMobile({
    mobile: mobile.value,
    code: code.value,
    openId: id.value
  })
  // 提示用户
  showSuccessToast('登录成功')
  // 存储用户信息
  userStore.setUser(res.data)
  // 跳转到”我的“页面
  router.replace('/user')
}
</script>

<template>
  <div class="login-page" v-if="!isBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form" @submit="bind">
      <van-field
        v-model="mobile"
        :rules="mobileRule"
        name="mobile"
        placeholder="请输入手机号"
      ></van-field>
      <van-field v-model="code" :rules="codeRule" name="code" placeholder="请输入验证码">
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}
          </span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button style="margin-top: 50px" block round type="primary" native-type="submit">
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    padding: 30px 30px 50px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
</style>
